package com.happyfamily.springboot.crowdsourcingplatform.controller.sun;

import com.google.gson.Gson;
import com.happyfamily.springboot.crowdsourcingplatform.annotation.OperationLogDetail;
import com.happyfamily.springboot.crowdsourcingplatform.base.result.Results;
import com.happyfamily.springboot.crowdsourcingplatform.enums.OperationType;
import com.happyfamily.springboot.crowdsourcingplatform.enums.OperationUnit;
import com.happyfamily.springboot.crowdsourcingplatform.model.*;
import com.happyfamily.springboot.crowdsourcingplatform.service.sun.BankService;
import com.happyfamily.springboot.crowdsourcingplatform.service.sun.NewService;
import com.happyfamily.springboot.crowdsourcingplatform.service.sun.SysUserService;
import com.happyfamily.springboot.crowdsourcingplatform.service.sun.AllianceService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/api-front/alliance/")
public class AllianceController
{
	@Autowired
	private AllianceService allianceServiceImpl;

	@Autowired
	private SysUserService userServiceImpl;

	@Autowired
	private BankService bankServiceImpl;

	@Autowired
	private NewService newServiceImpl;

	@RequestMapping("getList")
	@ResponseBody
	@ApiOperation(value = "服务商查询所有与自己无关的联盟信息", notes = "服务商查询所有与自己无关的联盟信息", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "服务商查询所有与自己无关的联盟信息", level = 1, operationUnit = OperationUnit.USER, operationType = OperationType.SELECT)
	public String getList(HttpServletRequest request, String limit, String page, String aname)
	{
		SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String account = securityContextImpl.getAuthentication().getName();
		SysUser sysUser = userServiceImpl.getUser(account);

		TableModel tableModel = new TableModel();
		tableModel.setMsg("");
		tableModel.setCode(0);
		tableModel.setCount(allianceServiceImpl.getSum(sysUser.getUid(), aname));
		List<Alliance> list = allianceServiceImpl.getList(sysUser.getUid(), Integer.valueOf(limit), Integer.valueOf(page), aname);
		for (Alliance alliance : list)
		{
			alliance.setTips3(allianceServiceImpl.getServerType(Long.valueOf(alliance.getAtype())));
		}
		tableModel.setData(list);
		Gson g = new Gson();
		return g.toJson(tableModel);
	}

	@RequestMapping("getList2")
	@ResponseBody
	@ApiOperation(value = "服务商查询所有与自己相关的联盟信息", notes = "服务商查询所有与自己相关的联盟信息", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "服务商查询所有与自己相关的联盟信息", level = 1, operationUnit = OperationUnit.USER, operationType = OperationType.SELECT)
	public String getList2(HttpServletRequest request, String limit, String page, String aname)
	{
		SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String account = securityContextImpl.getAuthentication().getName();
		SysUser sysUser = userServiceImpl.getUser(account);

		TableModel tableModel = new TableModel();
		tableModel.setMsg("");
		tableModel.setCode(0);
		tableModel.setCount(allianceServiceImpl.getSum(sysUser.getUid(), aname));
		List<Alliance> list = allianceServiceImpl.getList2(sysUser.getUid(), Integer.valueOf(limit), Integer.valueOf(page), aname);
		for (Alliance alliance : list)
		{
			alliance.setTips3(allianceServiceImpl.getServerType(Long.valueOf(alliance.getAtype())));
			boolean flag = allianceServiceImpl.checkAlliance(sysUser.getUid(), alliance.getAid());
			if (flag)
			{
				alliance.setTips1("盟主");
			} else
			{
				User_alliance ua = allianceServiceImpl.getUa(alliance.getAid(), sysUser.getUid());
				alliance.setTips2(ua.getUastate());
			}
		}
		tableModel.setData(list);
		Gson g = new Gson();
		return g.toJson(tableModel);
	}

	@RequestMapping("checkAccount")
	@ResponseBody
	@ApiOperation(value = "检查联盟账号是否存在", notes = "检查联盟账号是否存在", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "检查联盟账号是否存在", level = 1, operationUnit = OperationUnit.USER, operationType = OperationType.SELECT)
	public String checkAccount(String aaccount)
	{
		String str = "no";
		boolean flag = allianceServiceImpl.checkAccount(aaccount);
		if (flag)
		{
			str = "yes";
		}
		return str;
	}

	@RequestMapping("newAlliance")
	@ResponseBody
	@ApiOperation(value = "服务商创建联盟", notes = "服务商创建联盟", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "服务商创建联盟", level = 3, operationUnit = OperationUnit.USER, operationType = OperationType.INSERT)
	public String newAlliance(String aname, String ainfo, String amoney, String uastate, String aaccount, HttpServletRequest request)
	{
		String str = "no";
		SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String account = securityContextImpl.getAuthentication().getName();
		SysUser sysUser = userServiceImpl.getUser(account);
		Alliance alliance = new Alliance();
		alliance.setAname(aname);
		alliance.setAinfo(ainfo);
		if (amoney.contains("."))
		{
			amoney = amoney.substring(0, amoney.indexOf("."));
		}
		alliance.setAmargin(amoney);
		alliance.setAaccout(aaccount);
		alliance.setAbank(aaccount);
		alliance.setAmasterid(sysUser.getUid() + "");
		alliance.setAtype(uastate);
		allianceServiceImpl.addAlliance(alliance);
		User_alliance ua = new User_alliance();
		ua.setAid(alliance.getAid());
		ua.setUid(sysUser.getUid());
		ua.setUastate("运行中");
		Bank bank = new Bank();
		bank.setBaccount(aaccount);
		bankServiceImpl.addBank(bank);
		boolean flag = allianceServiceImpl.addUserAlliance(ua);
		if (flag)
		{
			str = "yes";
		}
		return str;
	}

	@RequestMapping("addAlliance")
	@ResponseBody
	@ApiOperation(value = "服务商申请加入某个联盟", notes = "服务商申请加入某个联盟", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "服务商申请加入某个联盟", level = 5, operationUnit = OperationUnit.USER, operationType = OperationType.ALL)
	public String addAlliance(HttpServletRequest request, String aid, String money)
	{
		String str = "noMoney";
		SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String account = securityContextImpl.getAuthentication().getName();
		SysUser sysUser = userServiceImpl.getUser(account);
		if (Double.valueOf(sysUser.getUmoney()) >= Double.valueOf(money))
		{
			double sum = Double.valueOf(sysUser.getUmoney()) - Double.valueOf(money);
			userServiceImpl.updateMoney(sum + "", sysUser.getUid());
			User_alliance ua = new User_alliance();
			ua.setAid(Long.valueOf(aid));
			ua.setUid(sysUser.getUid());
			ua.setUastate("待审核");
			boolean flag = allianceServiceImpl.addUserAlliance(ua);
			if (flag)
			{
				str = "yes";
			}
		}
		return str;
	}

	@RequestMapping("backAlliance")
	@ResponseBody
	@ApiOperation(value = "服务商退出联盟", notes = "服务商退出联盟", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "服务商退出联盟", level = 5, operationUnit = OperationUnit.USER, operationType = OperationType.ALL)
	public String backAlliance(HttpServletRequest request, String aid, String money)
	{
		Alliance alliance=allianceServiceImpl.getAlliance(Long.valueOf(aid));
		SysUser magrin=userServiceImpl.getUserById(Long.valueOf(alliance.getAmasterid()));
		String str = "no";
		SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String account = securityContextImpl.getAuthentication().getName();
		SysUser sysUser = userServiceImpl.getUser(account);
		userServiceImpl.updateMoney(Double.valueOf(money) + Double.valueOf(sysUser.getUmoney()) + "", sysUser.getUid());
		boolean flag = allianceServiceImpl.backAlliance(Long.valueOf(aid), sysUser.getUid());
		if (flag)
		{
			str = "yes";
			News news=new News();
			news.setUaccount(magrin.getUaccount());
			news.setNtime(new SimpleDateFormat("YYYY-MM-dd").format(new Date()));
			news.setNtext("您的联盟:【"+alliance.getAname()+"】中的【"+sysUser.getUname()+"("+sysUser.getUaccount()+")】已退出联盟");
			newServiceImpl.addNews(news);
			userServiceImpl.updateCount(magrin.getUaccount(),magrin.getNewcount()+1);
		}
		return str;
	}

	@RequestMapping("deleteAlliance")
	@ResponseBody
	@ApiOperation(value = "服务商解散联盟", notes = "服务商解散联盟", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "服务商解散联盟", level = 5, operationUnit = OperationUnit.USER, operationType = OperationType.ALL)
	public String deleteAlliance(String aid, String money, String account, HttpServletRequest request)
	{
		Alliance alliance=allianceServiceImpl.getAlliance(Long.valueOf(aid));
		String str = "no";
		SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String acc = securityContextImpl.getAuthentication().getName();
		SysUser sysUser = userServiceImpl.getUser(acc);
		boolean flag = allianceServiceImpl.checkOrder(Long.valueOf(aid));
		if (flag)
		{
			List<User_alliance> list = allianceServiceImpl.getUsers(Long.valueOf(aid));
			for (User_alliance ua : list)
			{
				if (!(sysUser.getUid().toString().equals(ua.getUid() + "")))
				{
					SysUser user = userServiceImpl.getUserById(ua.getUid());
					userServiceImpl.updateMoney(Double.valueOf(user.getUmoney()) + Double.valueOf(money) + "", ua.getUid());
					News news=new News();
					news.setUaccount(user.getUaccount());
					news.setNtime(new SimpleDateFormat("YYYY-MM-dd").format(new Date()));
					news.setNtext("您的联盟:【"+alliance.getAname()+"】已解散");
					newServiceImpl.addNews(news);
					userServiceImpl.updateCount(sysUser.getUaccount(),sysUser.getNewcount()+1);
				}
				bankServiceImpl.deleteBank(account);
			}
			allianceServiceImpl.deleteAlliance(Long.valueOf(aid));
			allianceServiceImpl.deleteAll(Long.valueOf(aid));
			str = "yes";
		}
		return str;
	}

	@RequestMapping("getUsers")
	@ResponseBody
	@ApiOperation(value = "服务商获取某个联盟所有成员信息", notes = "服务商获取某个联盟所有成员信息", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "服务商获取某个联盟所有成员信息", level = 1, operationUnit = OperationUnit.USER, operationType = OperationType.SELECT)
	public String getUsers(String page, String aid, HttpServletRequest request)
	{
		SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String account = securityContextImpl.getAuthentication().getName();
		TableModel tableModel = new TableModel();
		tableModel.setCode(0);
		tableModel.setMsg("");
		List<User_alliance> list = allianceServiceImpl.getUsers(Long.valueOf(aid));
		List<SysUser> users = new ArrayList<>();
		for (User_alliance ua : list)
		{
			if (ua.getUastate().equals("运行中"))
			{
				SysUser sysUser = userServiceImpl.getUserById(ua.getUid());
				if (!(sysUser.getUaccount().equals(account)))
				{
					String type = allianceServiceImpl.getServerType(Long.valueOf(sysUser.getSid()));
					sysUser.setTips1(type);
					users.add(sysUser);
				}
			}
		}
		tableModel.setCount(users.size());
		int p = Integer.valueOf(page);
		int n = 5 * (p - 1);
		List<SysUser> userList = new ArrayList<>();
		int sum = users.size() - 1;
		if (n + 4 <= users.size() - 1)
		{
			sum = n + 4;
		}
		for (int i = n; i <= sum; i++)
		{
			userList.add(users.get(i));
		}
		tableModel.setData(userList);
		;
		Gson g = new Gson();
		return g.toJson(tableModel);
	}


	@RequestMapping("getUsers2")
	@ResponseBody
	@ApiOperation(value = "服务商获取某个联盟所有申请情况", notes = "服务商获取某个联盟所有申请情况", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "服务商获取某个联盟所有申请情况", level = 1, operationUnit = OperationUnit.USER, operationType = OperationType.SELECT)
	public String getUsers2(String page, String aid)
	{
		TableModel tableModel = new TableModel();
		tableModel.setCode(0);
		tableModel.setMsg("");
		List<User_alliance> list = allianceServiceImpl.getUsers(Long.valueOf(aid));
		List<SysUser> users = new ArrayList<>();
		for (User_alliance ua : list)
		{
			if (ua.getUastate().equals("待审核"))
			{
				SysUser sysUser = userServiceImpl.getUserById(ua.getUid());
				String type = allianceServiceImpl.getServerType(Long.valueOf(sysUser.getSid()));
				sysUser.setTips1(type);
				users.add(sysUser);
			}
		}
		tableModel.setCount(users.size());
		int p = Integer.valueOf(page);
		int n = 5 * (p - 1);
		List<SysUser> userList = new ArrayList<>();
		int sum = users.size() - 1;
		if (n + 4 <= users.size() - 1)
		{
			sum = n + 4;
		}
		for (int i = n; i <= sum; i++)
		{
			userList.add(users.get(i));
		}
		tableModel.setData(userList);
		Gson g = new Gson();
		return g.toJson(tableModel);
	}

	@RequestMapping("outAlliance")
	@ResponseBody
	@ApiOperation(value = "服务商将某个成员踢出联盟", notes = "服务商将某个成员踢出联盟", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "服务商将某个成员踢出联盟", level = 5, operationUnit = OperationUnit.USER, operationType = OperationType.ALL)
	public String outAlliance(String uid, String aid, String money)
	{
		String str = "no";
		SysUser sysUser = userServiceImpl.getUserById(Long.valueOf(uid));
		userServiceImpl.updateMoney(Double.valueOf(sysUser.getUmoney()) + Double.valueOf(money) + "", sysUser.getUid());
		boolean flag = allianceServiceImpl.backAlliance(Long.valueOf(aid), sysUser.getUid());
		if (flag)
		{
			str = "yes";
			News news=new News();
			news.setUaccount(sysUser.getUaccount());
			news.setNtime(new SimpleDateFormat("YYYY-MM-dd").format(new Date()));
			Alliance alliance=allianceServiceImpl.getAlliance(Long.valueOf(aid));
			news.setNtext("您所在的联盟:【"+alliance.getAname()+"】已将您踢出联盟");
			newServiceImpl.addNews(news);
			userServiceImpl.updateCount(sysUser.getUaccount(),sysUser.getNewcount()+1);
		}
		return str;
	}

	@RequestMapping("updateState")
	@ResponseBody
	@ApiOperation(value = "服务商对某个申请进行审核", notes = "服务商对某个申请进行审核", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "服务商对某个申请进行审核", level = 5, operationUnit = OperationUnit.USER, operationType = OperationType.ALL)
	public String updateState(String aid, String uid, String money, String type, String account)
	{
		String str = "no";
		SysUser sysUser=userServiceImpl.getUserById(Long.valueOf(uid));
		if (type.equals("同意"))
		{
			boolean flag = allianceServiceImpl.updateState(Long.valueOf(aid), Long.valueOf(uid), "运行中");
			if (flag)
			{
				News news=new News();
				news.setUaccount(sysUser.getUaccount());
				news.setNtime(new SimpleDateFormat("YYYY-MM-dd").format(new Date()));
				Alliance alliance=allianceServiceImpl.getAlliance(Long.valueOf(aid));
				news.setNtext("您申请的联盟:【"+alliance.getAname()+"】已同意您的申请");
				newServiceImpl.addNews(news);
				userServiceImpl.updateCount(sysUser.getUaccount(),sysUser.getNewcount()+1);
				str = "yes";
			}
		} else
		{
			userServiceImpl.updateMoney(Double.valueOf(sysUser.getUmoney()) + Double.valueOf(money) + "", sysUser.getUid());
			boolean flag = allianceServiceImpl.backAlliance(Long.valueOf(aid), sysUser.getUid());
			if (flag)
			{
				str = "yes";
				News news=new News();
				news.setUaccount(sysUser.getUaccount());
				news.setNtime(new SimpleDateFormat("YYYY-MM-dd").format(new Date()));
				Alliance alliance=allianceServiceImpl.getAlliance(Long.valueOf(aid));
				news.setNtext("您申请的联盟:【"+alliance.getAname()+"】已拒绝了您的申请");
				newServiceImpl.addNews(news);
				userServiceImpl.updateCount(sysUser.getUaccount(),sysUser.getNewcount()+1);
			}
		}
		return str;
	}

	@RequestMapping("getMyAlliance")
	@ResponseBody
	@ApiOperation(value = "服务商获取自己所有创建的联盟", notes = "服务商获取自己所有创建的联盟", httpMethod = "POST", response = String.class)
	@OperationLogDetail(detail = "服务商获取自己所有创建的联盟", level = 1, operationUnit = OperationUnit.USER, operationType = OperationType.SELECT)
	public List<Alliance> getMyAlliance(HttpServletRequest request)
	{
		List<Alliance> list = new ArrayList<>();
		SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String account = securityContextImpl.getAuthentication().getName();
		SysUser sysUser = userServiceImpl.getUser(account);
		list = allianceServiceImpl.getMyAlliance(sysUser.getUid());
		return list;
	}

}